/*
   @Copyright:LintCode
   @Author:   tjyemail
   @Problem:  http://www.lintcode.com/problem/count-and-say
   @Language: C++
   @Datetime: 16-02-09 04:47
   */

class Solution {
public:
	/**
	 * @param n: the nth
	 * @return: the nth sequence
	 * Tip:
	 * 1, 11, 21, 1211, 111221, 312211
	 */
	string countAndSay(int n) {
		// write your code here
		string res="1";
		char str[32];
		int count;
		for(int i=1; i<n; ++i){
			string tmp;
			count=1;
			for(int j=1; j<res.length(); ++j){
				if(res[j]!=res[j-1]){
					sprintf(str,"%d%c",count,res[j-1]);
					tmp.append(str);
					count=1;
				}
				else ++count;
			}
			sprintf(str,"%d%c",count,res.back());
			tmp.append(str);
			res=tmp;
		}
		return res;
	}
};
